package top.yamhk.agent.utils;

import lombok.extern.slf4j.Slf4j;
import top.yamhk.agent.entity.KernelNode;
import top.yamhk.agent.entity.dto.Message;
import top.yamhk.agent.entity.enums.MsgType;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 消息工具类
 *
 * @author 庆 HongKong
 * @date 2019/5/10 22:24
 */
@Slf4j
public class MsgUtils {

    /**
     * 私有构造方法
     */
    private MsgUtils() {
    }

    /**
     * 消息包
     */
    public static Message messagePackage(MsgType msgType, String content, KernelNode currentNode) {
        /* 实例 */
        Message message = new Message();
        //
        //KernelNode currentNode = SubBioClient.getCurrentNode();
        if (currentNode != null) {
            message.setRemark(currentNode.getRemark());
            message.setCharset(currentNode.getClientCharset());
            message.setMsgFrom(currentNode.getUsername());
            message.setAddressee(currentNode.getNickname());
        }
        //
        message.setContent(content);
        message.setItemType(msgType.getCode());
        message.setItemDesc(msgType.getDesc());
        return message;
    }

    public static Message serverHeartbeat(KernelNode kernelNode) {
        Message message = new Message();
        /* 实例 */
        message.setCharset("UTF8");
        message.setFrUserId("sys");
        message.setToUserId("all");
        message.setMsgFrom(kernelNode != null ? kernelNode.getUsername() : "CoreServer4");
        message.setAddressee("-1");
        message.setItemType(MsgType.HEART_BEAT_01.getCode());
        message.setItemDesc(MsgType.HEART_BEAT_01.getDesc());
        message.setMsgGroup(Integer.toString(MsgType.HEART_BEAT_01.getCode()));
        message.setRemark("sleep x seconds>?<");
        message.setContent("server heatBeat");
        return message;
    }

    public static Message messagePull(BlockingQueue<Message> queue, Function<KernelNode, Message> function, KernelNode kernelNode) {
        //有数据时直接从队列的队首取走，无数据时阻塞，在10min内有数据，取走，超过10s还没数据，返回失败
        Message message = null;
        try {
            message = queue.poll(kernelNode == null ? 3600 : 600, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("消息队列获取消息异常：{}", e.getMessage());
        }
        //五分钟之内
        //没有消息时发送心跳
        message = (message == null) ? function.apply(kernelNode) : message;
        return message;
    }
}